﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class SwitchboardOperatorModule : IHttpModule {

    public void Dispose() { }

    public void Init(HttpApplication context) {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e) {
        HttpApplication app = sender as HttpApplication;

        // Get key
        string key = app.Request.AppRelativeCurrentExecutionFilePath.ToLower();
        key = key.Substring(1).TrimEnd('/');

        // Ignore exception
        if (key.StartsWith("/app_") || key.StartsWith("/administration") || key.EndsWith(".axd")) return;

        // Find redirect URL
        using (var dc = new SwitchboardDataContext()) {
            var entry = dc.Entries.SingleOrDefault(x => x.Host.HostName == app.Request.Url.Host.ToLower() && x.LocalPath == key);

            if (entry == null) {
                // No redirect found, send ~/default.htm
                app.Response.StatusCode = 404;
                app.Response.StatusDescription = "Object Not Found";
                app.Response.WriteFile(app.Server.MapPath("~/default.htm"));
            }
            else {
                // Construct redirect response
                app.Response.StatusCode = entry.RedirectType.StatusCode;
                app.Response.StatusDescription = entry.RedirectType.StatusDescription;
                if (entry.RedirectType.UseLocationHeader) app.Response.AppendHeader("Location", entry.RedirectLocation);
                app.Response.Output.Write(entry.RedirectType.ResponseBody,
                    entry.RedirectLocation,
                    app.Request.Url,
                    entry.RedirectType.StatusCode,
                    entry.RedirectType.StatusDescription);
            }
            app.CompleteRequest();
        }
    }

}
